let isRecording = false;
let highlightElement = null;
let sidebar = null;
let elementsList = [];

// 创建侧边栏
function createSidebar() {
    // 如果侧边栏已存在则移除
    if (sidebar) {
        sidebar.remove();
    }

    // 创建侧边栏容器
    sidebar = document.createElement('div');
    sidebar.id = 'element-recorder-sidebar';
    sidebar.innerHTML = `
        <div class="sidebar-header">
            <h3>元素选择器记录器</h3>
            <button id="toggle-recording">开始记录</button>
            <button id="clear-all">清空</button>
        </div>
        <div class="sidebar-content">
            <p class="recording-status">未记录任何元素</p>
            <ul id="elements-list"></ul>
        </div>
    `;
    document.body.appendChild(sidebar);

    // 添加事件监听
    document.getElementById('toggle-recording').addEventListener('click', toggleRecording);
    document.getElementById('clear-all').addEventListener('click', clearAllElements);
}

// 切换记录状态
function toggleRecording() {
    isRecording = !isRecording;
    const toggleBtn = document.getElementById('toggle-recording');
    const statusEl = document.querySelector('.recording-status');

    if (isRecording) {
        toggleBtn.textContent = '停止记录';
        toggleBtn.classList.add('recording');
        statusEl.textContent = '正在记录...点击页面元素';
        document.addEventListener('click', handleElementClick, true);
        document.body.style.cursor = 'crosshair';
    } else {
        toggleBtn.textContent = '开始记录';
        toggleBtn.classList.remove('recording');
        statusEl.textContent = elementsList.length > 0 ? '记录已停止' : '未记录任何元素';
        document.removeEventListener('click', handleElementClick, true);
        document.body.style.cursor = '';
    }
}

// 生成元素选择器
function generateSelector(element) {
    if (element.tagName === 'HTML') return 'html';

    let selector = element.tagName.toLowerCase();

    // 如果有ID，使用ID选择器
    if (element.id) {
        return `${selector}#${element.id}`;
    }

    // 添加类选择器
    if (element.className) {
        const classes = element.className.trim().split(/\s+/);
        selector += '.' + classes.join('.');
    }

    // 如果是唯一的，直接返回
    if (document.querySelectorAll(selector).length === 1) {
        return selector;
    }

    // 否则添加nth-child选择器
    let parent = element.parentNode;
    if (parent) {
        const siblings = Array.from(parent.children);
        const index = siblings.indexOf(element) + 1;
        return generateSelector(parent) + ` > ${selector}:nth-child(${index})`;
    }

    return selector;
}

// 处理元素点击
function handleElementClick(e) {
    if (!isRecording) return;

    e.preventDefault();
    e.stopPropagation();

    const element = e.target;

    // 提取元素信息
    const elementInfo = {
        id: Date.now(), // 用于标识唯一元素
        tagName: element.tagName,
        id: element.id || '无',
        className: element.className || '无',
        value: element.value ? element.value : (element.textContent ? element.textContent.trim() : '无'),
        selector: generateSelector(element)
    };

    // 添加到列表
    elementsList.unshift(elementInfo);
    updateElementsList();

    // 短暂高亮选中的元素
    highlightElement = element;
    element.style.outline = '2px solid #4CAF50';

    setTimeout(() => {
        if (highlightElement) {
            highlightElement.style.outline = '';
            highlightElement = null;
        }
    }, 1000);
}

// 更新元素列表显示
function updateElementsList() {
    const listEl = document.getElementById('elements-list');
    const statusEl = document.querySelector('.recording-status');

    if (elementsList.length === 0) {
        listEl.innerHTML = '';
        statusEl.textContent = '未记录任何元素';
        return;
    }

    statusEl.textContent = `已记录 ${elementsList.length} 个元素`;
    listEl.innerHTML = elementsList.map(el => `
        <li class="element-item">
            <div class="element-info">
                <div><strong>标签名:</strong> ${el.tagName}</div>
                <div><strong>ID:</strong> ${el.id}</div>
                <div><strong>类名:</strong> ${el.className}</div>
                <div><strong>值:</strong> ${el.value}</div>
                <div><strong>选择器:</strong> <code>${el.selector}</code></div>
            </div>
            <button class="copy-btn" data-selector="${el.selector}">复制选择器</button>
        </li>
    `).join('');

    // 添加复制按钮事件
    document.querySelectorAll('.copy-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const selector = e.target.getAttribute('data-selector');
            navigator.clipboard.writeText(selector).then(() => {
                const originalText = btn.textContent;
                btn.textContent = '已复制!';
                setTimeout(() => {
                    btn.textContent = originalText;
                }, 2000);
            });
        });
    });
}

// 清空所有记录
function clearAllElements() {
    elementsList = [];
    updateElementsList();
}

// 初始化
window.addEventListener('load', () => {
    createSidebar();
});
